package org.obs.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.UserDetails;
import org.obs.core.GrantedAuthorityImpl;
import org.obs.core.UserDetailsImpl;

@Entity
@Table(name = "USERS")
public class User implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	@Column(name = "email", unique = true)
	private String email;

	@Column(name = "pwd")
	private String password;

	@Column(name = "roles")
	private String roles;
	
	@Column(unique=true, nullable=false)
	private String nick;

	@OneToOne(fetch = FetchType.LAZY, optional = false)
	private Blog blog;

	public Blog getBlog() {
		return blog;
	}

	public void setBlog(Blog blog) {
		this.blog = blog;
	}

	public String getRoles() {
		return roles;
	}

	public void setRoles(String roles) {
		this.roles = roles;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public UserDetails getUserDeatails() {
		return new UserDetailsImpl(getAuthorities(), getEmail(), getPassword(),
				true, true, true, true);
	}

	private GrantedAuthority[] getAuthorities() {
		String[] r = getRoles().split(",");
		GrantedAuthority[] auths = new GrantedAuthorityImpl[r.length];
		for (int i = 0; i < r.length; i++) {
			GrantedAuthority a = new GrantedAuthorityImpl(r[i]);
			auths[i] = a;
		}
		return auths;
	}

	public String getNick() {
		return nick;
	}

	public void setNick(String nick) {
		this.nick = nick;
	}

}
